# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSFaultRepair(Document):
	# 保存前自动计算维修完成时间
	def before_save(self):
		h1 = frappe.utils.time_diff_in_hours(self.finish_date, self.happen_date) #根据日期计算小时差
		h2 = frappe.utils.time_diff_in_hours(self.ems_finish_time, self.ems_happen_time) #根据时间计算小时差
		self.finish_hours = h1 + h2

	# 校验是否已经存在维修单
	def before_insert(self):
		if frappe.db.exists({"doctype": "EMS Fault Repair", "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] }):
			frappe.throw(_("EMS Fault Repair Is Created. The BillNo is:{0}").format(frappe.db.exists({"doctype": "EMS Fault Repair", "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] })))

	# 故障维修保存时更新故障报修之状态
	def after_insert(self):
		frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()


	# 故障维修删除时更新故障报修之状态
	def after_delete(self):
		frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()

	# 故障维修取消时更新故障报修之状态
	def on_cancel(self):
		frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()


# 故障维修单下推验收结算单
@frappe.whitelist()
def make_acceptance_settlement(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS Fault Repair",
		source_name,
		{
			"EMS Fault Repair": {
				"doctype": "EMS Acceptance Settlement",
				"field_map": {},
				"validation": {"docstatus": ["=", 1],},
			},
			"EMS Spair Parts Item": {
				"doctype": "EMS Settlement Item",
				"field_map": {},
				# "postprocess": update_item,
				# "condition": lambda doc: abs(doc.received_qty) < abs(doc.qty)
				# and doc.delivered_by_supplier != 1,
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc

# 故障维修单下推外部维修单: 20240926, 取消此路线, AB两个路线不允许交叉
# @frappe.whitelist()
# def make_external_maintenance(source_name, target_doc=None, args=None):
# 	doc = get_mapped_doc(
# 		"EMS Fault Repair",
# 		source_name,
# 		{
# 			"EMS Fault Repair": {
# 				"doctype": "EMS External Maintenance",
# 				"field_map": {},
# 				"validation": {"docstatus": ["=", 1], "send_for_repair": ["=", 1]},
# 			},
# 		},
# 		target_doc,
# 		ignore_permissions=True,
# 	)

# 	return doc